#include <QProcess>
#include <QDebug>
#include <QByteArray>
#include <QFileDialog>
#include <QMessageBox>
#include <QVariant>
#include <sys/statfs.h>
#include <stdio.h>
#include "worktool.h"

WorkTool::WorkTool(QObject *parent) :
    QObject(parent)
{
}

void WorkTool::execBashFile(QString filePath)
{
    process.start(filePath);
}

QString WorkTool::getDiskSize()
{
    QProcess p;
    QByteArray buf;
    QString size;


    p.start("bash /getDiskSize.sh");
    p.waitForFinished();
    buf = p.readAllStandardOutput();
    size = QString(buf).section('.', 0, 0);
    size.append("G");
    //qDebug() << buf;
    return size;

}

// ntfsclone
QString WorkTool::readBashOutput()
{
    QByteArray buf =  process.readAllStandardOutput();
    QString allBuf = QString(buf);
    QString lastLineBuf;
    QString savingDiskName;

    int posPercent = 0;
    int posSpeed = 0;
    int posSpendTime = 0;
    int percentVal = 0;
    QString percent;
    QString speed;
    QString spendTime;
    QString splitString;
    QString optDiskField;


    if (1 == st)
    {
        optDiskField = "WQJSAVEDISKNAME";
        splitString = "stdout";
    }
    else if (2 == st)
    {
        optDiskField = "WQJSTOREDISKNAME";
        splitString = "stdin";
    }
    else
    {
        return "status in normal, ERROR";
    }
    if (allBuf.contains(optDiskField))
    {
        lastLineBuf = allBuf.section("WQJSAVEDISKNAME", 1, 1);
        savingDiskName = lastLineBuf.section("\n", 0, 0, QString::SectionSkipEmpty);
        emit showOptDev(QVariant(savingDiskName));
    }
    if (allBuf.contains(splitString))
    {
        lastLineBuf = allBuf.section(splitString, -1);


        // percent
        posPercent = lastLineBuf.lastIndexOf("P:");
        percent = lastLineBuf.mid(posPercent+2);
        percent.remove('%');
        percent.remove(' ');
        percent.remove('\n');
        percentVal = percent.toInt();
        qDebug() << "percent" << percent;

        // speed
        posSpeed = lastLineBuf.lastIndexOf("R:");
        speed = lastLineBuf.mid(posSpeed+2, posPercent - posSpeed - 2);
        speed.remove(' ');
        qDebug() << "speed:" << speed;

        // Spend Time
        posSpendTime = lastLineBuf.lastIndexOf("T:");
        spendTime = lastLineBuf.mid(posSpendTime + 2, posSpeed - posSpendTime - 2);
        spendTime.remove(' ');
        qDebug() << "spend time:" << spendTime;

        if (speed.contains("M/min") || speed.contains("G/min"))
        {
            if ((percentVal > 1) && (percentVal <= 100))
            {
                emit showProc(QVariant(percentVal));
            }
            if (!speed.isEmpty())
            {
                emit showSpeed(QVariant(speed));
            }
            if (!spendTime.isEmpty())
            {
                emit showSpendTime(QVariant(spendTime));
            }
            QString rst = QString("Operating Device: %1; Spend Time: %2; Speed: %3; Percent: %4")
                    .arg(savingDiskName)
                    .arg(spendTime)
                    .arg(speed)
                    .arg(percent);
            //rst.clear();
            return rst;
        }
        else {
            allBuf.clear();
            return allBuf;
        }
    }
    return allBuf;


}

// partclone
QString WorkTool::readBashOutput1()
{
    QByteArray buf =  process.readAllStandardOutput();
    QString allBuf = QString(buf);
    QString tmp;
    QString percent;
    QString speed;
    QString spendTime;
    QString optDiskField;
    QString remainTime;
    QRegExp splitString("(WWW-->)");

    if (allBuf.contains("WWW-->"))
    {
        tmp = allBuf.section(splitString, -1);
        tmp = tmp.section('\n', 0, 0);
        spendTime = tmp.section(",", 0, 0).remove(QRegExp("^ "));
        emit showSpendTime(QVariant(spendTime));
        remainTime = tmp.section(",", 1, 1).remove(QRegExp("^ "));
        emit showRemainingTime(QVariant(remainTime));
        percent = tmp.section(",", 2, 2).remove(QRegExp("^ "));
        percent = percent.section(":", -1);
        percent.chop(1);
        emit showProc(QVariant(percent.toDouble()));
        speed = tmp.section(",", 3, 3).remove(QRegExp("^ ")).remove('\n');
        emit showSpeed(QVariant(speed));
        // allBuf.clear();

    }
    if (allBuf.contains("Backup image finished!"))
    {
        system("sleep 2");
        QMessageBox::information(NULL, "Image Recovery Utility",
                                   "Backup image finished",
                                   QMessageBox::Ok,
                                   QMessageBox::Ok);
    }
    if (allBuf.contains("Restore image finished!"))
    {
        system("sleep 2");
        QMessageBox::information(NULL, "Image Recovery Utility",
                                   "Restore image finished",
                                   QMessageBox::Ok,
                                   QMessageBox::Ok);
    }
    return allBuf;
}


void WorkTool::setStatus(int s)
{
    this->st = s;
}

bool WorkTool::confirmCancel()
{
    QMessageBox::StandardButton rst;

    rst = QMessageBox::question(NULL, "Image Recovery Utility",
                           "Do you really want to cancel?",
                           QMessageBox::Yes | QMessageBox::No,
                           QMessageBox::No);
    if (rst == QMessageBox::Yes)
    {
        return true;
    }
    else
    {
        return false;
    }
}

void WorkTool::shutDownDevice()
{
    QMessageBox::StandardButton rst;

    rst = QMessageBox::question(NULL, "Image Recovery Utility",
                           "Do you really want to poweroff the device?",
                           QMessageBox::Yes | QMessageBox::No,
                           QMessageBox::No);
    if (rst == QMessageBox::Yes)
    {
        system("poweroff");
    }
}

void WorkTool::stopCurrentTask()
{
    process.kill();
}

QString WorkTool::getImageDir()
{
    QString imageName;
    QString imageSize;
    QString info;
    int size_image;
    int size_disk;
    QString dir = QFileDialog::getExistingDirectory(NULL, tr("Open Directory"),
                                                    tr( "/home/partimage/"),
                                                     QFileDialog::ShowDirsOnly
                                                     | QFileDialog::DontResolveSymlinks | QFileDialog::ReadOnly);
    //qDebug() << "dir:" << dir;
    imageName = dir.section('/', -1);
    //qDebug() <<"imageName:" << imageName;
    imageSize = imageName.section('-', -2, -2).remove('G');
    //qDebug() << "imageSize:" << imageSize;
    size_image = imageSize.toInt();
    size_disk = getDiskSize().remove('G').toInt();
    //qDebug() << "size_image:" << size_image <<";size_disk:" << size_disk;
    if (size_image > size_disk)
    {
        info = QString("Image size(%1G) is bigger than the disk size(%2G), couldn't restore.").arg(size_image).arg(size_disk);
        QMessageBox::information(NULL, "Image Recovery Utility",
                                   info,
                                   QMessageBox::Ok,
                                   QMessageBox::Ok);
        return "";
    }

    return dir.section('/', -1);
}
